//
//  UserInfoEditViewController.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/22.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class UserInfoEditViewController: ViewController {

    @IBOutlet weak var doneBtn: UIButton! {
        didSet {
            doneBtn.layer.cornerRadius = 3
            doneBtn.layer.masksToBounds = true
            doneBtn.rx.tap
                .map { [unowned self] _ in self.editName }
                .bind(to: doneSubject)
                .disposed(by: bag)
        }
    }
    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.bounces = false
            tableView.register(UINib(resource: R.nib.userInfoEditCell), forCellReuseIdentifier: "\(UserInfoEditCell.self)")
        }
    }
    
    private var editName = ""
    
    let doneSubject = PublishSubject<String>()
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        view.endEditing(true)
    }

    @IBAction func cancelDidTap(_ sender: UIButton) {
        safeDismiss()
    }
}

extension UserInfoEditViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(UserInfoEditCell.self)", for: indexPath)
        if let editCell = cell as? UserInfoEditCell {
            editCell.textField.rx.text
                .orEmpty
                .do(onNext: { [weak self] text in
                    self?.editName = text
                })
                .map { $0.count > 0 && $0 != AccountManager.share.user.name }
                .bind(to: doneBtn.rx.isEnableTap)
                .disposed(by: bag)
        }
        return cell
    }
}

extension UserInfoEditViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "修改名字"
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
}
